package com.example;

import org.apache.zookeeper.KeeperException;

import java.io.IOException;
import java.util.ArrayList;

public class DistributeLockTest {

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {

        ArrayList<DistributeLock> locks = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            DistributeLock lock = new DistributeLock();
            locks.add(lock);
        }

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(new Runnable() {

                @Override
                public void run() {

                    try {
                        locks.get(finalI).lock();
                        System.out.println("线程" + (finalI + 1) + "启动，获取锁");
                        Thread.sleep(5000);
                        locks.get(finalI).unlock();
                        System.out.println("线程" + (finalI + 1) + "释放锁");
                    } catch (InterruptedException | KeeperException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

    }

}
